/**
 * coorder's default view.
 *
 * depends on underscore and backbone
 */

var FG;
if (!FG)
    FG = {};

FG.coordZhNameDict = {
    version: '版本',
    level: '高度',
    time: '时间'
};

FG.CoordView = Backbone.View.extend({
    className: 'coord',
    parent: null,

    renderOld: function() {
        var head = '<div class="' + this.className + '">' +
            '<div class="label ' + (this.model.get('can_poly') ? 'poly' : '') +
                '">' + FG.coordZhNameDict[this.model.get('name')] + '</div>' +
            //(this.model.get('can_poly') ?
            //    ('<div class="button poly ' + (this.model.get('mode') === 'poly' ? 'active' : '') + '"></div>'):
            //    '') +
            '<div class="button prev"></div>' +
            '<div class="list_container">' +
                '<ul>';
        var tail;
        if (this.model.get('customizable')) {
            tail = '</ul>' + '<input class="new" type="text">' + '</div>' +
                '<div class="button next"></div>' +
                '</div>'
        } else {
            tail = '</ul>' + '</div>' +
                '<div class="button next"></div>' +
                '</div>'
        }
        var currentSelects = this.model.getSelects();
        var activeI = 0;
        var middleList = _.map(this.model.get('values'), function(v) {
            var classStr = (_.indexOf(currentSelects, v) !== -1) ? "coorditem active active_" +  (activeI++) % 7 : "coorditem";
            return '<li class="' + classStr + '">' + String(v) + '</li>'
        });
        var result = [head, middleList.join(''), tail].join('');
        this.$el.html(result);
        if (typeof this.model.firstShownIndex === 'undefined') {
            this.model.firstShownIndex = 0;
        }
        for (var i=0; i <this.model.firstShownIndex; i++) {
            this.$el.find('.coorditem').eq(i).css('display', 'none');
        }
        return this;
    },

    render: function() {
        var this_ = this;
        
        // this.undelegateEvents();
        this.$el.empty();
        
        var colorNum,
            plotColors = FG.getSetting('plot.colors', ["#7cb5ec", "#fc8d62", "#a6d854", "#ffd92f", "#e78ad2", "#66c2a5", "#e5c494"]);
        try {
            colorNum = plotColors.length;
        } catch (e) {
            colorNum = 7;
        }
        
        this.$el.unbind("move");
        this.scrollbar = null;
        var head = '<div class="' + this.className + '">' +
                '<div class="viewport">' +
                    '<div class="overview">';
        var tail;
        tail = '</div>' +
                '</div>' +
                '<div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div></div>' +
                '<div class="label ' + (this.model.get('can_poly') ? 'poly' : '') +
                    '">' + FG.coordZhNameDict[this.model.get('name')] + '</div>' +
            '</div>';
        var currentSelects = this.model.getSelects();
        var activeI = 0;
        var firstActiveIndex;
        var middleList = _.map(this.model.get('values'), function(v, i) {
            var classStr,
                ci;
            if (_.indexOf(currentSelects, v) !== -1){
                ci = (activeI++) % colorNum;
                classStr = "coorditem active active_" + ci;
                if (typeof(firstActiveIndex) === 'undefined') {
                    firstActiveIndex = i;
                }
            } else {
                classStr = "coorditem";
            }
            return '<div class="' + classStr + '" style="background-color: ' + plotColors[ci] +';">' + String(v) + '</div>'
        });
        var result = [head, middleList.join(''), tail].join('');
        this.$el.html(result);
        if (!this.$el || this.$el.length === 0) {
            return this;
        }
        if (this.$el.data('plugin_tinyscrollbar')) {
            this.$el.removeData('plugin_tinyscrollbar');
        }
        var $track = this.$el.find('.track');

        if ($track.height() === 0 && $track.width() === 0) {
            // do nothing.
        } else if ($track.height() > $track.width()) {
            this.$el.tinyscrollbar();
            this.scrollbar = this.$el.data("plugin_tinyscrollbar");
        } else {
            var totalSize = 0;
            this.$el.find('.coorditem').each(function(i, item) {
                totalSize += $(item).outerWidth(true);
            });
            this.$el.find('.overview').width(totalSize);
            if (totalSize < this.$el.find('.viewport').width()) {
                this.$el.find('.viewport').width(totalSize);
                this.$el.find('.scrollbar').width(totalSize);
                //this.$el.find('.label').css('right', totalSize);
            }
            this.$el.tinyscrollbar({axis: 'x'});
            this.scrollbar = this.$el.data("plugin_tinyscrollbar");
            this.scrollbar.update(this.lastScrollbarPosition);

            if (typeof(firstActiveIndex) !== 'undefined' && !!this.scrollbar) {

                var scrollTo = firstActiveIndex / this.model.get('values').length * totalSize;
                var maxScrollTo = totalSize - this.scrollbar.viewportSize;
                var actualScrollTo = (scrollTo > maxScrollTo) ? maxScrollTo : scrollTo;
                // 只在目标不可见的时候进行移动
                if (scrollTo - this.lastScrollbarPosition >= this.scrollbar.viewportSize) {
                    this.scrollbar.update(actualScrollTo);
                } else if (scrollTo - this.lastScrollbarPosition < 0) {
                    this.scrollbar.update(actualScrollTo);
                }
            }
            this.lastScrollbarPosition = this.scrollbar.contentPosition;
        }
        if (!!this.scrollbar) {
            this.$el.bind("move", function() {
                this_.lastScrollbarPosition = this_.scrollbar.contentPosition;
            });
        }
        // this.delegateEvents();
        this.$('.coorditem').unbind().click(function(e) {
            e.stopPropagation();
            DX.print($(e.target).html());
            var sel = $(e.target).html(); // TODO: 更可靠的获取方式.
    
            if (ctrlPressed) {
                if (this_.model.get('can_poly')) {
                    if (this_.parent) {
                        this_.parent.resetAllPoly([this_]);
                    }
                    this_.model.set('mode', 'poly');
                }
            } else {
                this_.model.set('mode', 'mono')
            }
    
            var mode = this_.model.get('mode');
            if (mode === 'mono') {
                this_.model.setSelects([sel]);
            } else if (mode === 'poly') {
                var currentSels = this_.model.getSelects();
                if (_.indexOf(currentSels, sel) === -1) {
                    this_.model.setSelects(_.union(currentSels, [sel]));
                } else {
                    if (currentSels.length > 1) {
                        this_.model.setSelects(_.without(currentSels, sel));
                    }
                }
            }
        });
        return this;
    },

    events: {
        // TODO: toggle or set
        // 'click .coorditem': function(e) {
        //     e.stopPropagation();
        //     DX.print($(e.target).html());
        //     var sel = $(e.target).html(); // TODO: 更可靠的获取方式.
        //
        //     if (ctrlPressed) {
        //         if (this.model.get('can_poly')) {
        //             if (this.parent) {
        //                 this.parent.resetAllPoly([this]);
        //             }
        //             this.model.set('mode', 'poly');
        //         }
        //     } else {
        //         this.model.set('mode', 'mono')
        //     }
        //
        //     var mode = this.model.get('mode');
        //     if (mode === 'mono') {
        //         this.model.setSelects([sel]);
        //     } else if (mode === 'poly') {
        //         var currentSels = this.model.getSelects();
        //         if (_.indexOf(currentSels, sel) === -1) {
        //             this.model.setSelects(_.union(currentSels, [sel]));
        //         } else {
        //             if (currentSels.length > 1) {
        //                 this.model.setSelects(_.without(currentSels, sel));
        //             }
        //         }
        //     }
        // }
        //'mousewheel': function(e) {
        //    var delta = Math.abs(e.deltaY) > Math.abs(e.deltaX) ? e.deltaY : e.deltaX;
        //    //DX.warn(delta);
        //    //var func = delta > 0 ? this.showPrev : this.showNext;
        //    for (var i=0; i<Math.abs(delta); i+=1) {
        //        if (delta > 0) {
        //            this.showPrev(e);
        //        } else {
        //            this.showNext(e);
        //        }
        //    }
        //    e.stopPropagation();
        //}
        //'click .label': "toggleFullUL"
    },

    initialize: function() {
        this.firstShownIndex = 0;
        this.lastScrollbarPosition = 0;
        this.listenTo(this.model, "change", this.render);
    },

    showPrev: function(e) {
        if (typeof this.model.firstShownIndex === 'undefined') {
            this.model.firstShownIndex = 0;
        }
        if (this.model.firstShownIndex > 0) {
            this.model.firstShownIndex -= 1;
            this.$el.find('.coorditem').eq(this.model.firstShownIndex).css('display', 'block');
        }
        e.stopPropagation();
    },

    showNext: function(e) {
        if (typeof this.model.firstShownIndex === 'undefined') {
            this.model.firstShownIndex = 0;
        }
        if (this.model.firstShownIndex < this.model.get('values').length - 1 ) {
            this.$el.find('.coorditem').eq(this.model.firstShownIndex).css('display', 'none');
            this.model.firstShownIndex += 1;
        }
        e.stopPropagation();
    },

    //toggleFullUL: function(e) {
    //    this.$el.find('.list_container').css('height', this.$el.find('ul').css('height'))
    //},

    clear: function() {
        this.$el.empty();
    }
});

FG.CoorderView = Backbone.View.extend({
    initialize: function() {
        this.coordViews = {}
    },

    switchCoorder: function(coorder) {
        var this_ = this;
        this.clear();
        this.coorder = coorder;
        _.each(this.coorder.get('coords'), function(coord) {
            var name = coord.get('name');
            var elnameDict = {
                'time': '.time_coord_box',
                'level': '.level_coord_box',
                'version': '.version_coord_box',
                'domain': '.version_coord_box',
                'resolution': '.version_coord_box'
            };
            var $el = this_.$(elnameDict[name]);
            var cv = new FG.CoordView({model: coord});
            cv.parent = this_;
            cv.$el = $el;
            this_.coordViews[coord.get('name')] = cv;  // TODO: name or uuid?
            cv.render();
        })
    },

    resetAllPoly: function(excludes) {
        _.each(this.coordViews, function(cv) {
            if (_.contains(excludes, cv))
                return;
            if (cv.model.get('can_poly') && cv.model.get('mode') === 'poly') {
                cv.model.setSelects([cv.model.getSelects()[0]]);
                cv.model.set('mode', 'mono');
                //cv.render();
            }
        })
    },
    
    clear: function() {
        _.each(this.coordViews, function(cv){
            cv.clear();
        });
        this.stopListening();
    }
});
